﻿using System;

namespace Microsoft.Popfly.GameCreator.GameEngine.Events
{
    public class RandomIntervalChecker : IEventChecker
    {
        private Game m_game;
        private double m_minIntervalInSeconds;
        private double m_maxIntervalInSeconds;
        private double m_thisIntervalInSeconds;
        private double m_totalElapsedTimeInSeconds;

        private double GenerateRandomInterval()
        {
            double range = m_maxIntervalInSeconds - m_minIntervalInSeconds;
            return m_minIntervalInSeconds + range * m_game.RandomNumberGenerator.NextDouble();
        }

        public RandomIntervalChecker(Game game, double minIntervalInSeconds, double maxIntervalInSeconds)
        {
            m_game = game;
            m_minIntervalInSeconds = minIntervalInSeconds;
            m_maxIntervalInSeconds = maxIntervalInSeconds;
            m_totalElapsedTimeInSeconds = 0;

            m_thisIntervalInSeconds = GenerateRandomInterval();
        }

        #region IEventChecker Members

        public bool FireThisFrame(double elapsedTimeInSeconds, out BehaviorOwner sender, out PGCEventArgs args)
        {
            m_totalElapsedTimeInSeconds += elapsedTimeInSeconds;

            if (m_totalElapsedTimeInSeconds >= m_thisIntervalInSeconds)
            {
                sender = m_game.CurrentScene;
                args = null;
                
                m_totalElapsedTimeInSeconds -= m_thisIntervalInSeconds;

                m_thisIntervalInSeconds = GenerateRandomInterval();

                return true;
            }
            else
            {
                sender = null;
                args = null;

                return false;
            }
        }

        public bool IsOfEventType(string eventType)
        {
            return eventType == "timer" || eventType == "Timer";
        }

        #endregion
    }
}